package graphics.Meshes;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.media.opengl.GL;

import common.Point3D;


public class MeshObject extends AbstractMesh {

	String filename = null;
	double pointsRotationX = 0;
	double pointsRotationY = 0;
	double pointsRotationZ = 0;
	
	
	public void setParameter(String name, String params[]){
		
		if (name.equals("filename")) {
			this.filename = params[0];
			return;
		}
		if (name.equals("protate")) {
			this.pointsRotationX = Double.parseDouble(params[0])/ 180 * Math.PI;;
			this.pointsRotationY = Double.parseDouble(params[1])/ 180 * Math.PI;;
			this.pointsRotationZ = Double.parseDouble(params[2])/ 180 * Math.PI;;
			return;
		}
		super.setParameter(name, params);
	}
	
	
	public void readMesh() throws IOException
	{
		
		
		FileReader sr=null;
		try {
			sr = new FileReader(filename);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		int vertNum, facesNum;
		
		
		BufferedReader r = new BufferedReader(sr);
		String header =  r.readLine();
		
		//(the mesh file is .OFF)
		if (header.equals("OFF")){
			String line = r.readLine();
			String[] meshInfo = line.split(" ");
			vertNum = Integer.parseInt(meshInfo[0]);
			facesNum = Integer.parseInt(meshInfo[1]);
		}else{ //(the mesh file is .PLY)
			vertNum = Integer.parseInt(header);
			facesNum = Integer.parseInt(r.readLine());
		}
	
		
		for (int i=0; i<vertNum; i++){
			String[] vert_line = (r.readLine()).split(" ");
			double v0 = (double)Double.parseDouble(vert_line[0]);
			if (Math.abs(v0)<0.00001)
				v0=0;
			double v1 = (double)Double.parseDouble(vert_line[1]);
			if (Math.abs(v1)<0.00001)
				v1=0;

			double v2 = (double)Double.parseDouble(vert_line[2]);
			if (Math.abs(v2)<0.00001)
				v2=0;
				
			Point3D point = new Point3D(v0, v1, v2);
			point.rotate(pointsRotationX, pointsRotationY, pointsRotationZ);
			points.add(point);	   
		}
		for (int i=0; i<facesNum; i++){
			String[] triangleLine = (r.readLine()).split(" ");
			int v0 = Integer.parseInt(triangleLine[1]);
			int v1 = Integer.parseInt(triangleLine[2]);
			int v2 = Integer.parseInt(triangleLine[3]); 
	
			Trigon tr = new Trigon(points.get(v2), points.get(v1), points.get(v0));

			trigons.add(tr);
		}
		
		r.close();
		
	}
	public void initialize(GL gl) {
		super.initialize(gl);

		
		if (filename!= null){
		try {
			readMesh();
		} catch (Exception e) {
			System.out.println("Error failed to read texture");
			e.printStackTrace();
			primaryTexture = null;
		}}
		
		super.initialize(gl);
		
	}

}
